package com.stedu.security;


import cn.hutool.json.JSONUtil;
import com.stedu.bean.RespBean;
import com.stedu.utils.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/*登陆成功处理器
*1.返回登录成功的信息
*2.生成jwt返回给前端
*
* */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler  {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");

        //生成jwt
        String username = request.getParameter("username");
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        String s = JwtUtils.generateJwt(map);
        RespBean error = RespBean.ok("登陆成功",s);

        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJsonStr(error));//转换json
        writer.flush();
        writer.close();
    }
}
